package cn.jeeweb.modules.task.task;

import cn.jeeweb.core.query.data.Condition;
import cn.jeeweb.core.query.data.QueryRequest;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.utils.SpringContextHolder;
import cn.jeeweb.core.utils.sms.SmsManager;
import cn.jeeweb.core.utils.sms.data.SmsTemplate;
import cn.jeeweb.modules.flood.client.GetFloodInfoClient;
import cn.jeeweb.modules.flood.client.floodinfoapi.FloodRainFullClient;
import cn.jeeweb.modules.flood.entity.FloodRainfull;
import cn.jeeweb.modules.flood.entity.FloodSite;
import cn.jeeweb.modules.flood.entity.FloodSiteWarn;
import cn.jeeweb.modules.flood.entity.SrFloodWarnLog;
import cn.jeeweb.modules.flood.service.IFloodRainfullService;
import cn.jeeweb.modules.flood.service.IFloodSiteService;
import cn.jeeweb.modules.flood.service.IFloodSiteWarnService;
import cn.jeeweb.modules.flood.service.ISrFloodWarnLogService;
import com.ff.common.util.format.DateUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

import static org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace;

/**
 * @Author:Wish
 * @Date: Created in 2018/12/16 15:42
 **/
@Component
public class RainfullTask {
    public final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    IFloodSiteWarnService floodSiteWarnService;


    @Autowired
    ISrFloodWarnLogService floodWarnLogService;


    public void run() {
        log.info(" run start......................................" + (new Date()));
        Date yesDay = DateUtil.dayCalculate(DateUtil.getCurrentDate(), -3);
        IFloodSiteService floodSiteService = SpringContextHolder.getBean("floodSiteService");

        List<FloodSite> floodSites = floodSiteService.listWithNoPage(new QueryRequest());
        for (FloodSite temp : floodSites) {
            getRainFullInfo(temp, DateUtil.DateToString(yesDay, "yyyy-MM-dd"), DateUtil.DateToString(new Date(), "yyyy-MM-dd"));
        }
        log.error("run finish");

    }

    public void getRainFullInfo(FloodSite floodSite, String starTime, String endTime) {
        try {
            IFloodRainfullService floodRainfullService = SpringContextHolder.getBean("floodRainfullService");
            log.info("rainfull-----------------site:" + floodSite.getSiteName() + "begin-------------------");
            GetFloodInfoClient client = new FloodRainFullClient()
                    .setReqParam(floodSite.getScid(), starTime, endTime);
            Map<String, Object> responseMap = client.getFloodInfo();
            //删除上次拉取记录
            floodRainfullService.delete(new EntityWrapper<FloodRainfull>()
                    .between("record_time", starTime, endTime)
                    .eq("record_type", 0)
                    .eq("site_id", floodSite.getId()));
            if (null != responseMap) {
                Map<String, Object> response = ((List<Map<String, Object>>) responseMap.get("responses")).get(0);
                if (null != response) {
                    Map<String, Object> data = (Map<String, Object>) response.get("data");
                    if (null != data) {

                        //查询站点警戒设置
                        EntityWrapper<FloodSiteWarn> entityWrapper1 = new EntityWrapper<>();
                        entityWrapper1.eq("parent_id", floodSite.getId());
                        List<FloodSiteWarn> floodSiteWarns = floodSiteWarnService.selectList(entityWrapper1);
                        Map<Integer, FloodSiteWarn> floodSiteWarnMap = new HashMap<>();
                        List<Integer> list = new ArrayList<>();
                        if (null != floodSiteWarns && floodSiteWarns.size() > 0) {
                            for (FloodSiteWarn temp : floodSiteWarns) {
                                if (null != temp.getThreshold() && temp.getThreshold() > 0) {
                                    floodSiteWarnMap.put(temp.getThreshold(), temp);
                                    list.add(temp.getThreshold());
                                }
                            }
                        }

                        Collections.sort(list, new Comparator<Integer>() {
                            public int compare(Integer o1, Integer o2) {
                                return o1.compareTo(o2);
                            }
                        });


                        List<String> hq = (List<String>) data.get("HQ");
                        List<String> tm = (List<String>) data.get("TM");
                        if (null != hq && null != tm && hq.size() == tm.size()) {
                            for (int i = 0; i < hq.size(); i++) {
                                FloodRainfull entity = new FloodRainfull();
                                BeanUtils.copyProperties(floodSite, entity);
                                entity.setSiteId(floodSite.getId());
                                entity.setId(null);
                                double rainfull = Double.parseDouble(hq.get(i));
                                Date date = DateUtil.stringToDate(tm.get(i));
                                try {
                                    if (rainfull > list.get(0)) {
                                        EntityWrapper<FloodRainfull> entityWrapper = new EntityWrapper<>();
                                        entityWrapper.eq("site_id", floodSite.getId());
                                        entityWrapper.eq("record_time", date);
                                        entityWrapper.eq("record_type", 0);
                                        List<FloodRainfull> floodRainfulls = floodRainfullService.selectList(entityWrapper);
                                        if (floodRainfulls == null || floodRainfulls.size() == 0) {
                                            for (int j = 1; j < list.size(); j++) {
                                                if (rainfull > list.get(j - 1) && rainfull < list.get(j)) {
                                                    SrFloodWarnLog warnLog = new SrFloodWarnLog();
                                                    warnLog.setSiteId(floodSite.getId());
                                                    warnLog.setSiteKind(floodSite.getKind());
                                                    warnLog.setSiteName(floodSite.getSiteName());
                                                    warnLog.setSiteType(floodSite.getType());
                                                    warnLog.setWarnInfo(floodSiteWarnMap.get(list.get(j - 1)).getRemarks() +
                                                            "[" + floodSite.getSiteName() + " 降雨量已经高于阈值" + list.get(j) + "]");
                                                    floodWarnLogService.insert(warnLog);
                                                    String templateContent = "雨量报警信息：{1}。";
                                                    SmsTemplate smsTemplate = SmsTemplate.newTemplateByContent(templateContent);
                                                    SmsManager.getSmsManager().send("15217723610", smsTemplate, warnLog.getWarnInfo());
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e1) {
                                    log.error("处理预警信息失败:" + ExceptionUtils.getFullStackTrace(e1));
                                }
                                entity.setRainfull(rainfull);
                                entity.setRecordTime(DateUtil.stringToDate(tm.get(i)));
                                entity.setRecordType(0);
                                floodRainfullService.insert(entity);
                                if (i == hq.size() - 1) {
                                    floodSite.setRainfall(Double.parseDouble(hq.get(i)));
                                    IFloodSiteService floodSiteService = SpringContextHolder.getBean("floodSiteService");
                                    floodSiteService.updateById(floodSite);
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取信息失败:" + e.getMessage());
        }
    }

}
